package com.dhecp.project.hr.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import com.alibaba.fastjson.JSON;
import com.dhecp.common.core.domain.AjaxResult;
import com.dhecp.common.utils.MessageUtils;
import com.dhecp.common.utils.RandomValueUtils;
import com.dhecp.core.constant.DataFiltering;
import com.dhecp.core.utils.PageUtils;
import com.dhecp.framework.util.ShiroUtils;
import com.dhecp.project.business.domain.ProductBasis;
import com.dhecp.project.business.mapper.ProductBasisMapper;
import com.dhecp.project.common.service.UpdateLogService;
import com.dhecp.project.common.service.impl.BaseModuleServiceImpl;
import com.dhecp.project.hr.domain.AmazonShopProduct;
import com.dhecp.project.hr.mapper.AmazonShopProductMapper;
import com.dhecp.project.hr.service.AmazonShopProductService;
import com.dhecp.project.system.service.SysDictionaryForFieldService;

/**
 * @program: kjecp
 * @description: 亚马逊店铺订单表
 * @author: hlf
 * @create: 2022-09-29 16:10
 */
@Service
public class AmazonShopProductServiceImpl extends BaseModuleServiceImpl implements AmazonShopProductService {

    @Autowired
    private AmazonShopProductMapper businessMapper;
    @Autowired
    private UpdateLogService updateLogService;
    @Autowired
    private SysDictionaryForFieldService dictionaryForFieldService;
    @Autowired
    private ProductBasisMapper productBasisMapper;


    /**
     * @Description: 查询
     * @Param: [params]
     * @return: java.util.List<com.dhecp.project.hr.domain.AmazonShopProduct>
     * @Author: hlf
     * @date: 2022-05-09 10:10
     */
    @Override
    public List<AmazonShopProduct> queryList(Map<String, Object> params) throws Exception {
        params.put(DataFiltering.TABLE_ALIAS, "t1");    //查询表别名
        params.put(DataFiltering.DATA_WHERE, dictionaryForFieldService.getWhereStr(params));    //常规查询条件SQL语句
        params.put(DataFiltering.DATA_SCODE, dictionaryForFieldService.getDataScode(params));    //数据权限查询条件SQL语句

        if (params.get("field") == null || params.get("field") == "") {
            String orderBy = "createTime asc";
            PageUtils.startPageOrder(orderBy);
        } else {
            PageUtils.startPage();
        }
        return businessMapper.select(params);
    }


    /**
     * @Description: 查询指定单nid的首记录
     * @Param: [params]
     * @return: com.dhecp.project.storage.domain.AmazonShopProduct
     * @Author: hlf
     * @date: 2022-05-09 10:10
     */
    @Override
    public AmazonShopProduct findByGuid(Map<String, Object> params) throws Exception {
        params.put(DataFiltering.TABLE_ALIAS, "t1");    //查询表别名
        params.put(DataFiltering.DATA_SCODE, dictionaryForFieldService.getDataScode(params));    //数据权限查询条件SQL语句
        return businessMapper.findById(params);
    }

    /**
     * @Description: 查询指定单nid的首记录
     * @Param: [params]
     * @return: com.dhecp.project.storage.domain.AmazonShopProduct
     * @Author: hlf
     * @date: 2022-05-09 10:10
     */
    @Override
    public List<AmazonShopProduct> findByProductCode(Map<String, Object> params) throws Exception {
        params.put(DataFiltering.TABLE_ALIAS, "t1");    //查询表别名
        params.put(DataFiltering.DATA_SCODE, dictionaryForFieldService.getDataScode(params));    //数据权限查询条件SQL语句
        return businessMapper.findByProductCode(params);
    }

    /**
     * @Description: 保存
     * @Param: [params] moduleTable 必要参数：功能唯一标识
     * @Param: [params] infoMap 必要参数：非网格字段（包括头部、底部所有显示和隐藏的字段）
     * @Param: [params] infoItems 必要参数：对应实体类的json格式字符串
     * @return: com.dhecp.common.core.domain.AjaxResult
     * @Author: hlf
     * @date: 2022-05-09 10:10
     */
    @Override
    @Transactional(timeout = 120, propagation = Propagation.REQUIRES_NEW)
    public AjaxResult saveData(Map<String, Object> params) {
        AmazonShopProduct oldData = new AmazonShopProduct();

        List<AmazonShopProduct> newData = JSON.parseArray(params.get("infoItems").toString(), AmazonShopProduct.class);

        Map<String, Object> params2 = new HashMap<String, Object>();
        List<Map<String, String>> skuList = new ArrayList<Map<String, String>>();
        for (AmazonShopProduct item : newData
        ) {
//            item.getSellerSku()
            ProductBasis productBasis = productBasisMapper.findProductBasisByCode(item.getCode());
            if (productBasis.getIsSuperior().equals("是")) {

                Map<String, String> sku = new LinkedHashMap<String, String>();
                sku.put("id", item.getSellerId());
                sku.put("sku", item.getSellerSku());
                sku.put("markId", item.getMarketplaceId());
                skuList.add(sku);

                for (Map<String, String> sid : skuList
                ) {
                    if (sid.get("id").equals(item.getSellerId()) && sid.get("markId").equals(item.getMarketplaceId())) {
                        if (!sid.get("sku").equals(item.getSellerSku())) {
                            return AjaxResult.error("同一个店铺不可添加不同的sku");
                        }
                    }
                }
            }

            params2.put("guid", item.getGuid());
            oldData = businessMapper.findById(params2);
            //有asin的网上商品信息不允许修改
            if (oldData != null) {
                if (oldData.getAsin() != null) {
                    if (!oldData.getSellerSku().equals(item.getSellerSku())) {
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        return AjaxResult.error("SKU已经关联Asin不允许修改SKU信息,如需修改请删除后重新关联!");
                    }
                    if (!oldData.getSellerId().equals(item.getSellerId())) {
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        return AjaxResult.error("SKU已经关联Asin不允许修改平台编码信息,如需修改请删除后重新关联!");
                    }
                }
            }

            List<AmazonShopProduct> productSku = businessMapper.findByProductSku(item.getSellerSku());//判断是否存在数据
            if (productSku.size() > 0) {
                for (AmazonShopProduct sku : productSku
                ) {
                    if (item.getSellerSku().equals(sku.getSellerSku())) {
                        //判断是否同公司
                        if (!item.getShopName().split("-")[0].equals(sku.getShopName().split("-")[0])){
                            return AjaxResult.error("当前SKU已存在不可重复添加");
                        }

                        //判断是否同大区
                        if (sku.getMarketplaceId().equals(item.getMarketplaceId()) && !Objects.equals(item.getGuid(), sku.getGuid())) {
                            return AjaxResult.error("当前SKU已存在不可重复添加");
                        }
                    } else {
                        return AjaxResult.error("当前SKU已存在不可重复添加");
                    }

                    //判断是否存在不同商品的SKU
                    if (!item.getCode().equals(sku.getCode())){
                        return AjaxResult.error("当前SKU已存在不可重复添加");
                    }
                }
            }

            if (item.getGuid() != null && !item.getGuid().equals("")) {

                item.setUpdateTime(new Date());
                item.setUpdateUser(ShiroUtils.getUserId());
                businessMapper.update(item);
                updateLogService.addUpdateLog(params.get("moduleTable").toString(), item.getGuid(), oldData, newData, "修改");
            } else {

                item.setGuid(RandomValueUtils.getGUID());
                item.setCreateTime(new Date());
                item.setCreateUser(ShiroUtils.getUserId());
                businessMapper.insert(item);
                updateLogService.addInsertLog(params.get("moduleTable").toString(), item.getGuid(), "新增");
            }
        }

        return AjaxResult.success(MessageUtils.message("module.success.issuccess"), newData.get(0).getGuid());
    }


    /**
     * @Description: 删除
     * @Param: [params]
     * @return: com.dhecp.common.core.domain.AjaxResult
     * @Author: hlf
     * @date: 2022-05-09 10:11
     */
    @Override
    public AjaxResult deleteData(Map<String, Object> params) {
        List<AmazonShopProduct> businessDataList = JSON.parseArray(params.get("infoItems").toString(), AmazonShopProduct.class);
        if (businessDataList == null || businessDataList.size() == 0) {
            return AjaxResult.error(MessageUtils.message("module.error.jsontoentyerror"));
        }
        for (AmazonShopProduct businessData : businessDataList) {
            businessMapper.delete(businessData);
        }
        return AjaxResult.success(MessageUtils.message("module.success.issuccess"));
    }

}